package com.itcg.springboot03deptemptest.service.impl;


import com.itcg.springboot03deptemptest.mapper.DeptMapper;
import com.itcg.springboot03deptemptest.pojo.Dept;
import com.itcg.springboot03deptemptest.pojo.Emp;
import com.itcg.springboot03deptemptest.service.DeptService;
import com.itcg.springboot03deptemptest.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpService empService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Dept> findAll() {
        List<Dept> depts = (List<Dept>) redisTemplate.boundValueOps("depts").get();
        //先排断Redis有没有数据
        if (depts !=null) {
            System.out.println("从Redis取数据");
            return depts;
        }
        //没有数据就从数据库里面取
        System.out.println("从MySQL数据库取数据");
        depts = deptMapper.findAll();
        //然后存一份到Redis中
        redisTemplate.boundValueOps("depts").set(depts);
        return depts;
    }

    @Override
    public Dept findById(Integer id) {
        return deptMapper.findById(id);
    }

    @Override
    @Transactional
    public void inserts(Dept dept) {
        deptMapper.inserts(dept);
    }

    @Override
    @Transactional
    public void deletes(Integer id) {
        deptMapper.deletes(id);
    }

    @Override
    @Transactional
    public void updates(Dept dept) {
        deptMapper.updates(dept);
    }

    @Override
    public Dept findWhenEmpById(Integer id) {
        Dept dept = findById(id);
        if (dept == null) {
            return null;
        }
        List<Emp> empList = empService.findEmpByDeptId(id);
        dept.setEmpList(empList);
        return dept;
    }

    @Override
    public void insertAll(Emp emp) {
        deptMapper.insertAll(emp);
    }
}
